#include "worker/worker.h"
#include "headers.h"
#include "our_header.h"
#include "service/feature_7th.h"
#include "tools/file_helper.h"
#include "tools/my_tlv.h"
#include <stdio.h>
#include <string.h>

int putsFileControl(int fd, MYSQL *conn, train_t *train) {

	train_t stdata = {0};
	// 先复制token
	extra_data_t *extoken = (extra_data_t *)train->data;
	memcpy(stdata.data, extoken, sizeof(extra_data_t));
	// 拆分文件信息
	file_mes_t *file_mes = (file_mes_t *)((char *)extoken + sizeof(extra_data_t));
	if(file_mes->file_len <= 0) {
		stdata.cmdstat = train->cmdstat | RES;
		char sent[] = "文件长度不正确";
		strcpy(stdata.data + sizeof(extra_data_t), sent);
		stdata.length = sizeof(extra_data_t) + strlen(sent);
		send_train(fd, &stdata);
		return -1;
	}
	int add_set = addFile_T(conn, extoken->cur_dir_id, file_mes->file_name, file_mes->file_hash, file_mes->file_len);
	if(add_set == 1) {
		stdata.cmdstat = train->cmdstat | RES;
		char sent[] = "文件名重复";
		strcpy(stdata.data + sizeof(extra_data_t), sent);
		stdata.length = sizeof(extra_data_t) + strlen(sent);
		send_train(fd, &stdata);
		return -1;
	};

	if(add_set == 2) {
		stdata.cmdstat = train->cmdstat | RES | IS_OK | SEFIE;
		char sent[] = "已有样本";
		strcpy(stdata.data + sizeof(extra_data_t), sent);
		stdata.length = sizeof(extra_data_t) + strlen(sent);
		send_train(fd, &stdata);
		return -1;
	}

	stdata.cmdstat = train->cmdstat| IS_OK ;
	stdata.length = sizeof(extra_data_t);
	send_train(fd, &stdata);

	char real_file_path[1024]={0};
	sprintf(real_file_path,"%s/%s",NETDISK_ROOT_DIR,file_mes->file_hash);
	recvFile_7ht(fd,real_file_path,file_mes->file_len,0);
	return 0;
}

void *workerTask(void *arg) {
	tdata_t *share_data = (tdata_t *)arg;
	SQItem train = {0};
	while(1) {
		printf("worker --- wait\n");
		int tag = consumSocketFd_h(&train);
		if(tag == 0) {
			switch(train.tra.cmdstat) {
			case PUTS: {
				int tag = putsFileControl(train.netfd, share_data->connect, &train.tra);
				printf("puts over tag:%d\n", tag);
				close(train.netfd);
			} break;
			default:
				close(train.netfd);
				break;
			}
		}
		if(tag) {
			printf("woker-----exit\n");
			break;
		}
		printf("worker --- woke finish\n");
	}
	pthread_exit(NULL);
	return NULL;
}